package com.iye.puretennis;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import com.iye.puretennis.activity.MainTabsActivity;
import com.iye.puretennis.activity.ProfileActivity;
import com.iye.puretennis.activity.RegisterActivity;
import com.iye.puretennis.custom.BaseActivity;
import com.iye.puretennis.custom.CustomApplication;
import com.iye.puretennis.custom.ExitApplication;
import com.iye.puretennis.domain.Gender;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.UserToken;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.DBManager;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.utils.ImageUtils;
import com.iye.puretennis.utils.JsonUtils;
import com.iye.puretennis.utils.StringUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

public class LoginActivity extends BaseActivity {

    Tencent mTencent;

    LoginInfo loginInfo;

    public static final int LOGIN = 1;
    public static final int USER_INFO = 2;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);

        CustomApplication application = (CustomApplication) getApplication();

        Typeface typeface = application.getHuaWenHuPo();

        if (typeface == null){
            application.setHuaWenHuPo(Typeface.createFromAsset(getAssets(), Constant.DEFAULT_FONT));
        }

            dbManager = new DBManager(this);

        LinearLayout loginMethodLayout = (LinearLayout) findViewById(R.id.login_method_layout);
        setLinearLayoutTopMargin(loginMethodLayout);

        final Button tencentLoginButton = (Button) findViewById(R.id.btn_tencent_login);
        tencentLoginButton.setTypeface(typeface);
        tencentLoginButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    tencentLoginButton.setAlpha(0.9f);
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    tencentLoginButton.setAlpha(1);
                }
                return false;
            }
        });
        tencentLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                qqLogin();
            }
        });
        final Button accountLoginButton = (Button) findViewById(R.id.btn_account_login);
        accountLoginButton.setTypeface(typeface);
        accountLoginButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    accountLoginButton.setAlpha(0.9f);
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    accountLoginButton.setAlpha(1);
                }
                return false;
            }
        });

        final Button loginButton = (Button) findViewById(R.id.loginBtn);
        loginButton.setTypeface(typeface);
        loginButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    loginButton.setAlpha(0.9f);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    loginButton.setAlpha(1);
                }
                return false;
            }
        });

        final Button accountLoginCancelButton = (Button) findViewById(R.id.btn_account_login_cancel);
        accountLoginCancelButton.setTypeface(typeface);
        accountLoginCancelButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    accountLoginCancelButton.setAlpha(0.9f);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    accountLoginCancelButton.setAlpha(1);
                }
                return false;
            }
        });

        final Button registerButton = (Button) findViewById(R.id.btn_register);
        registerButton.setTypeface(typeface);
        registerButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    registerButton.setAlpha(0.9f);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    registerButton.setAlpha(1);
                }
                return false;
            }
        });

        if (!hasNetWork()) {

            AlertDialog.Builder b = new AlertDialog.Builder(this).setTitle(getString(R.string.no_network)).setMessage(getString(R.string.no_network_warning));
            b.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
                    startActivity(intent);
                }
            }).setNeutralButton(getString(R.string.no), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                }
            }).show();
        }


        loginInfo = new LoginInfo();
        ExitApplication.getInstance().addActivity(this);
    }

    public void accountLogin(View view) {
        View loginMethodView = findViewById(R.id.login_method_layout);
        loginMethodView.setVisibility(View.GONE);
        LinearLayout accountLoginView = (LinearLayout) findViewById(R.id.account_login_layout);
        setLinearLayoutTopMargin(accountLoginView);
        accountLoginView.setVisibility(View.VISIBLE);

    }


    public void accountLoginCancel(View view) {
        View accountLoginView = findViewById(R.id.account_login_layout);

        accountLoginView.setVisibility(View.GONE);

        LinearLayout loginMethodView = (LinearLayout) findViewById(R.id.login_method_layout);
        setLinearLayoutTopMargin(loginMethodView);
        loginMethodView.setVisibility(View.VISIBLE);
    }

    private void setLinearLayoutTopMargin(LinearLayout loginMethodView) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) loginMethodView.getLayoutParams();
        layoutParams.topMargin = (int) (height * 0.45);
    }

    public void register(View view) {

        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

    }


    public void login(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EditText usernameView = (EditText) findViewById(R.id.username);
                EditText passwordView = (EditText) findViewById(R.id.password);
                String username = usernameView.getText().toString();
                String password = passwordView.getText().toString();
                process(username, password);
            }
        }).start();

    }

    private void process(String username, String password) {

        try {

            String rev = ServerAccessHelper.login(username, password);
            if (StringUtils.hasText(rev)) {
                JSONObject result = new JSONObject(rev);
                String guid = result.getString("guid");
                String token = result.getString("token");
                boolean setup = result.getBoolean("setup");
                dbManager.login(guid, token, setup ? 1 : 0);
                //start the profile activity
                Intent intent;
                if (setup) {
                    intent = new Intent(this, MainTabsActivity.class);
                } else {
                    intent = new Intent(this, ProfileActivity.class);
                }
                intent.putExtra("guid", guid);
                intent.putExtra("Access_Token", token);
                startActivity(intent);
                overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTencent.onActivityResult(requestCode, resultCode, data);
    }

    public void qqLogin() {
        mTencent = Tencent.createInstance(Constant.QQ_APP_ID, this.getApplicationContext());
        if (!mTencent.isSessionValid()) {
            BaseUiListener baseUiListener = new BaseUiListener(Constant.LOGIN);
            mTencent.login(this, Constant.GUID_ALL, baseUiListener);
        }
    }

    public void qqLogout() {
        mTencent.logout(this);
    }

    private class LoginInfo {

        String expiresIn;
        String openId;
        String accessToken;
        String nickName;
        String gender;
        String imageUri;
    }

    private class BaseUiListener implements IUiListener {

        private String type;

        public BaseUiListener(String type) {
            this.type = type;
        }

        protected void doComplete(JSONObject values) {
            try {
                Message msg = mHandler.obtainMessage();
                if (Constant.LOGIN.equals(type)) {
                    loginInfo.expiresIn = values.getString("expires_in");
                    loginInfo.accessToken = values.getString("access_token");
                    loginInfo.openId = values.getString("openid");

                    msg.what = LOGIN;
                } else if (Constant.USER_INFO.equals(type)) {
                    loginInfo.nickName = values.getString("nickname");
                    String gender = values.getString("gender");
                    loginInfo.gender = getString(R.string.male).equals(gender) ? Gender.MALE.name() : Gender.FEMALE.name();
                    loginInfo.imageUri = values.getString("figureurl_qq_2");
                    msg.what = USER_INFO;
                }
                mHandler.sendMessage(msg);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onComplete(Object o) {
            try {
                doComplete(new JSONObject(o.toString()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError e) {

        }

        @Override
        public void onCancel() {

        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGIN:
                    mTencent.setAccessToken(loginInfo.accessToken, loginInfo.expiresIn);
                    mTencent.setOpenId(loginInfo.openId);
                    com.tencent.connect.UserInfo userInfo = new com.tencent.connect.UserInfo(LoginActivity.this, mTencent.getQQToken());
                    userInfo.getUserInfo(new BaseUiListener(Constant.USER_INFO));

                    break;
                case USER_INFO:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            JSONObject paramJson = new JSONObject();
                            try {
                                paramJson.put("openId", loginInfo.openId);
                                paramJson.put("accessToken", loginInfo.accessToken);
                                paramJson.put("nickname", loginInfo.nickName);
                                paramJson.put("gender", loginInfo.gender);
                                StringEntity paramEntity = new StringEntity(paramJson.toString(), Constant.CHARSET_UTF8);
                                String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.USER_THIRD_PART_LOGIN), null, paramEntity);
                                if (!result.equals(Constant.RESPONSE_BADLY)) {
                                    UserToken userToken = JsonUtils.toUserToken(result);
                                    String guid = userToken.getGuid();
                                    String token = userToken.getToken();
                                    dbManager.login(guid, token, userToken.isSetup() ? 1 : 0);
                                    updateProfileImage(userToken);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                    break;

            }

        }
    };


    public void updateProfileImage(final UserToken userToken) {
        if (StringUtils.hasText(loginInfo.imageUri)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject profileJsonObj = new JSONObject();
                    try {
                        Bitmap imgBitmap = ImageUtils.getImgBitmap(loginInfo.imageUri);
                        String base64 = ImageUtils.bitmapToBase64(imgBitmap);
                        profileJsonObj.put("base64Bytes", base64);
                        StringEntity paramEntity = new StringEntity(profileJsonObj.toString(), Constant.CHARSET_UTF8);
                        String result = ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.PROFILE_IMAGE), userToken.getToken(), paramEntity);
                        if (!Constant.RESPONSE_BADLY.equals(result)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent;
                                    if (userToken.isSetup()) {
                                        intent = new Intent(LoginActivity.this, MainTabsActivity.class);
                                    } else {
                                        intent = new Intent(LoginActivity.this, ProfileActivity.class);
                                    }
                                    intent.putExtra("guid", userToken.getGuid());
                                    intent.putExtra("Access_Token", userToken.getToken());
                                    startActivity(intent);
                                    overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
                                }
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

}
